package com.bridgeintelligent.tag.bulkload.service.batch;

import com.bridgeintelligent.tag.bulkload.api.BulkLoadConfig;
import com.bridgeintelligent.tag.bulkload.api.BulkLoadException;
import com.bridgeintelligent.tag.bulkload.api.IndexNameInfo;
import com.bridgeintelligent.tag.bulkload.service.core.BulkEventDelegate;
import com.bridgeintelligent.tag.bulkload.service.core.refresh.BulkRefreshApi;
import com.bridgeintelligent.tag.bulkload.service.core.refresh.BulkRefreshApiUtils;
import com.bridgeintelligent.tag.bulkload.service.core.refresh.BulkRefreshConfig;
import com.bridgeintelligent.tag.bulkload.service.es.ESUtils;
import com.bridgeintelligent.tag.constants.bulkload.BulkLoadMqMsg;
import com.bridgeintelligent.tag.mapper.BatchDimFreeMapper;
import com.wayneleo.quickstart.framework.ExceptionCode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by JackCheung on 2019/9/23 2:21 AM.
 */
@AllArgsConstructor
@Service
@Slf4j
public class BatchService {

    private BatchDimFreeMapper batchDimFreeMapper;
    private BulkEventDelegate bulkEventDelegate;
    private BulkRefreshApiUtils bulkRefreshApiUtils;
    private BulkRefreshConfig bulkRefreshConfig;
    private static final String INDEX_SIGN = "03";

    /**
     * 自定义标签跑批执行任务
     *
     * @param indexName
     */
    public void doTask(String indexName) {
        long time = System.currentTimeMillis();
        //根据索引名获取主题和索引类型
        IndexNameInfo indexNameInfo = batchDimFreeMapper.getIndexNameInfoByIndex(indexName);
        String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        //自定义标签列表要跟主题挂钩
        List<BatchDimFreeDto> list = batchDimFreeMapper.dimList(date, indexNameInfo.getId())
                                                       .stream()
                                                       .filter(batchDimFreeDto -> StringUtils.isNotEmpty(batchDimFreeDto
                                                                                                                 .getFilePath()))
                                                       .peek(batchDimFreeDto -> {
                                                           if (INDEX_SIGN.equals(batchDimFreeDto.getClassify())) {
                                                               batchDimFreeDto.setFiledMapping("double");
                                                           }
                                                       })
                                                       .collect(Collectors.toList());
        Map<String, String> mappingMap = list.stream()
                                             .collect(Collectors.toMap(BatchDimFreeDto::getDimId,
                                                                       BatchDimFreeDto::getFiledMapping));
        //更新索引映射
        ESUtils.updateIndexMapping(indexName, indexNameInfo.getIndexType(), mappingMap);
        try {
            //循环执行批量任务
            list.forEach(batchDimFreeDto -> bulkEventDelegate.dispense(new BulkLoadMqMsg(batchDimFreeDto.getDimId(),
                                                                                         indexNameInfo.getId(),
                                                                                         batchDimFreeDto.getFilePath(),
                                                                                         batchDimFreeDto.getFilePath(),
                                                                                         batchDimFreeDto.getItemNo(),
                                                                                         BulkLoadConfig.BATCH_TYPE,
                                                                                         indexNameInfo.getIndexType(),
                                                                                         "",
                                                                                         false)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("自定义标签批量出现异常=======>", e);
            throw new BulkLoadException(new ExceptionCode(999, e.getMessage()));
        } finally {
            //刷新引擎缓存
            refreshEngineCache();
            log.debug("自定义批量耗时=====>{}ms", (System.currentTimeMillis() - time));
        }
    }

    /**
     * 刷新引擎缓存
     */
    private void refreshEngineCache() {
        String url = bulkRefreshConfig.getRequestUrl();
        BulkRefreshApi bulkRefreshApi = bulkRefreshApiUtils.build(BulkRefreshApi.class,
                                                                  url + BulkLoadConfig.REFRESH_PATH);
        bulkRefreshApi.refreshItem();
    }
}
